package com.example.demo.controller;

import com.example.demo.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
@RestController
@RequestMapping
public class TestController {

    @Autowired
    private TaskService taskService;

    @GetMapping("query")
    public void query() throws Exception {
        taskService.query();
    }



        public static void main(String[] args) {
            final int numberOfThreads = 5;
            CyclicBarrier cyclicBarrier = new CyclicBarrier(numberOfThreads, () -> {
                System.out.println("所有线程已到达屏障点，继续执行后续任务。");
            });

            for (int i = 0; i < numberOfThreads; i++) {
                new Thread(new Worker("Thread-" + i, cyclicBarrier)).start();
            }
        }

        static class Worker implements Runnable {
            private final String name;
            private final CyclicBarrier cyclicBarrier;

            public Worker(String name, CyclicBarrier cyclicBarrier) {
                this.name = name;
                this.cyclicBarrier = cyclicBarrier;
            }

            @Override
            public void run() {
                try {
                    System.out.println(name + " 正在执行任务...");
                    // 模拟任务执行时间
                    Thread.sleep((long) (Math.random() * 10));
                    System.out.println(name + " 到达屏障点，等待其他线程...");
                    cyclicBarrier.await();
                    System.out.println(name + " 继续执行...");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }
}
